<template>
  <div class="w-full max-w-md mx-auto">
    <HeaderComponent :score="score" :highScore="highScore" />
    <GameBoard 
      :snake="snake" 
      :food="food" 
      :cellSize="cellSize" 
      :gameActive="gameActive"
      @game-over="gameOver"
    />
    <Controls @direction-change="setDirection" v-if="isMobile" />
    <GameInfo v-if="!isMobile" />
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue'
import HeaderComponent from './components/HeaderComponent.vue'
import GameBoard from './components/GameBoard.vue'
import Controls from './components/Controls.vue'
import GameInfo from './components/GameInfo.vue'

// 游戏状态
const score = ref(0)
const highScore = ref(localStorage.getItem('snakeHighScore') || 0)
const snake = ref([])
const food = ref({})
const direction = ref('right')
const nextDirection = ref('right')
const gameSpeed = ref(150)
const gameActive = ref(false)
const cellSize = ref(20)
const gridSize = ref(20)
const gameInterval = ref(null)
const isMobile = ref(window.innerWidth < 768)

// 初始化游戏
const initGame = () => {
  const center = Math.floor(gridSize.value / 2)
  
  snake.value = [
    {x: center * cellSize.value, y: center * cellSize.value},
    {x: (center - 1) * cellSize.value, y: center * cellSize.value},
    {x: (center - 2) * cellSize.value, y: center * cellSize.value}
  ]
  
  generateFood()
  
  score.value = 0
  direction.value = 'right'
  nextDirection.value = 'right'
  gameActive.value = true
  gameSpeed.value = 150
  
  if (gameInterval.value) clearInterval(gameInterval.value)
  gameInterval.value = setInterval(gameLoop, gameSpeed.value)
}

// 游戏循环
const gameLoop = () => {
  direction.value = nextDirection.value
  
  moveSnake()
  
  if (checkCollision()) {
    gameOver()
    return
  }
  
  if (snake.value[0].x === food.value.x && snake.value[0].y === food.value.y) {
    score.value += 10
    if (score.value > highScore.value) {
      highScore.value = score.value
      localStorage.setItem('snakeHighScore', highScore.value)
    }
    generateFood()
    
    if (score.value % 50 === 0 && gameSpeed.value > 60) {
      gameSpeed.value -= 10
      clearInterval(gameInterval.value)
      gameInterval.value = setInterval(gameLoop, gameSpeed.value)
    }
  } else {
    snake.value.pop()
  }
}

// 移动蛇
const moveSnake = () => {
  const head = {x: snake.value[0].x, y: snake.value[0].y}
  
  switch(direction.value) {
    case 'up':
      head.y -= cellSize.value
      break
    case 'down':
      head.y += cellSize.value
      break
    case 'left':
      head.x -= cellSize.value
      break
    case 'right':
      head.x += cellSize.value
      break
  }
  
  snake.value = [head, ...snake.value]
}

// 检查碰撞
const checkCollision = () => {
  const head = snake.value[0]
  
  if (head.x < 0 || head.x >= gridSize.value * cellSize.value || 
      head.y < 0 || head.y >= gridSize.value * cellSize.value) {
    return true
  }
  
  for (let i = 1; i < snake.value.length; i++) {
    if (head.x === snake.value[i].x && head.y === snake.value[i].y) {
      return true
    }
  }
  
  return false
}

// 生成食物
const generateFood = () => {
  let overlapping
  
  do {
    overlapping = false
    food.value = {
      x: Math.floor(Math.random() * gridSize.value) * cellSize.value,
      y: Math.floor(Math.random() * gridSize.value) * cellSize.value
    }
    
    for (let segment of snake.value) {
      if (segment.x === food.value.x && segment.y === food.value.y) {
        overlapping = true
        break
      }
    }
  } while (overlapping)
}

// 游戏结束
const gameOver = () => {
  gameActive.value = false
  clearInterval(gameInterval.value)
}

// 重新开始游戏
const restartGame = () => {
  initGame()
}

// 设置方向
const setDirection = (newDirection) => {
  if (
    (newDirection === 'up' && direction.value === 'down') ||
    (newDirection === 'down' && direction.value === 'up') ||
    (newDirection === 'left' && direction.value === 'right') ||
    (newDirection === 'right' && direction.value === 'left')
  ) {
    return
  }
  
  nextDirection.value = newDirection
}

// 处理键盘事件
const handleKeydown = (e) => {
  switch(e.key) {
    case 'ArrowUp':
      setDirection('up')
      break
    case 'ArrowDown':
      setDirection('down')
      break
    case 'ArrowLeft':
      setDirection('left')
      break
    case 'ArrowRight':
      setDirection('right')
      break
    case ' ':
      if (!gameActive.value) restartGame()
      break
  }
}

// 响应窗口大小变化
const handleResize = () => {
  isMobile.value = window.innerWidth < 768
}

onMounted(() => {
  initGame()
  window.addEventListener('keydown', handleKeydown)
  window.addEventListener('resize', handleResize)
})

onBeforeUnmount(() => {
  window.removeEventListener('keydown', handleKeydown)
  window.removeEventListener('resize', handleResize)
  if (gameInterval.value) clearInterval(gameInterval.value)
})
</script>
    